<template>
  <div class="report-list">
    <!-- <div class="bread">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>顾问绩效管理</el-breadcrumb-item>
        <el-breadcrumb-item>顾问绩效</el-breadcrumb-item>
      </el-breadcrumb>
    </div> -->
    <div class="rl-content white-card">
      <div class="search-box" ref="searchBar">
        <el-form
          :model="form"
          ref="form"
          size="medium"
          label-width="80px"
          class="demo-form"
        >
          <el-row>
            <el-col :span="6">
              <el-form-item label="顾问姓名" prop="consultantName">
                <el-input
                  placeholder="请输入顾问"
                  v-model.trim="form.consultantName"
                  clearable
                  @clear="handleSearch"
                  @keyup.enter.native="handleSearch"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="所属部门" prop="appId">
                <el-cascader
                  v-model="form.deptIds"
                  :options="depTree"
                  :clearable="true"
                  filterable
                  placeholder="请选择所属部门"
                  style="width: 100%"
                  :props="{
                    label: 'dept',
                    value: 'dept_id',
                    children: 'gpc_second_class',
                  }"
                  @change="handleSearch"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <!-- <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item
                label="顾问类型"
                prop="applyType"
                label-width="100px"
              >
                <el-select
                  style="width: 100%;"
                  v-model="form.applyType"
                  placeholder="请选择顾问类型"
                  clearable
                  @change="handleSearch"
                >
                  <el-option
                    v-for="item in consultantTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    @change="handleSearch"
                  >
                    <span>{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="任务状态" prop="applyState">
                <el-select
                  style="width: 100%;"
                  v-model="form.applyState"
                  placeholder="请选择任务状态"
                  @change="handleSearch"
                >
                  <el-option
                    v-for="item in taskStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    @change="handleSearch"
                  >
                    <span>{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <el-form-item label="统计时间" prop="monthRange">
                <el-date-picker
                  style="width: 100%"
                  v-model="form.selectDate"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="20px">
                <el-button type="primary" size="small" @click="handleSearch"
                  >筛选</el-button
                >
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="table-wrap">
        <div class="operate-bar">
          <el-button
            plain
            round
            size="small"
            :loading="exportLoading"
            @click="exportAll"
            >{{ exportLoading ? "导出中..." : "导出数据" }}</el-button
          >
          <!-- <div class="tips">系统分和响应时间于当日24:00更新统计</div> -->
        </div>
        <div :style="{ height: tableHeight + 'px' }">
          <el-table
            :data="list"
            height="100%"
            v-loading="loading"
            highlight-current-row
            tooltip-effect="light"
            :header-cell-class-name="'header_name_style'"
          >
            <el-table-column
              type="index"
              width="75"
              align="center"
              label="序号"
            >
            </el-table-column>
            <el-table-column
              prop="consultantName"
              label="顾问姓名"
              min-width="100"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="consultantId"
              label="顾问ID"
              min-width="100"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="depName"
              label="部门"
              min-width="100"
              show-overflow-tooltip
            >
            </el-table-column>
            <!-- <el-table-column
              prop="score"
              label="系统绩效评分"
              min-width="100"
              align="center"
            >
              <template slot="header">
                <div class="my-header" @click="showTipsVisible = true">
                  <span class="title">系统绩效评分</span>
                  <i class="el-icon-question"></i>
                </div>
              </template>
              <template slot-scope="scope">
                <el-popover
                  placement="top-start"
                  title=""
                  popper-class="el-popover-self"
                  trigger="hover"
                >
                  <div class="list-box">
                    <div class="item" style="font-weight: 400; color: #999">
                      <span class="name">回复得分</span>
                      <span class="value">{{ scope.row.replyScore || 0 }}</span>
                    </div>
                    <div class="item">
                      <span class="name">评价得分</span>
                      <span class="value">{{ scope.row.rateScore || 0 }}</span>
                    </div>
                    <div class="item">
                      <span class="name">案例得分</span>
                      <span class="value">{{ scope.row.caseScore || 0 }}</span>
                    </div>
                    <div class="item">
                      <span class="name">报告得分</span>
                      <span class="value">{{
                        scope.row.reportScore || 0
                      }}</span>
                    </div>
                  </div>
                  <div slot="reference" class="currentName-3">
                    <div class="name pointer">
                      {{ scope.row.score || 0 }}
                    </div>
                  </div>
                </el-popover>
              </template>
            </el-table-column> -->
            <el-table-column label="用户评价" min-width="100">
              <template slot-scope="scope">
                <el-popover
                  placement="top-start"
                  title=""
                  popper-class="el-popover-self"
                  trigger="hover"
                >
                  <div class="list-box" v-loading="scoreLoading">
                    <div
                      class="item"
                      v-for="(item, index) in currentScoreList"
                      :key="index"
                    >
                      <span class="name">{{ item.label }}</span>
                      <span class="value">{{ item.value || 0 }}</span>
                    </div>
                  </div>
                  <div slot="reference" class="currentName-3">
                    <div
                      class="name pointer"
                      @mouseenter="handleGetScore(scope.row)"
                    >
                      {{ scope.row.userRate }}
                    </div>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              prop="reportCount"
              label="解析报告数"
              :show-overflow-tooltip="true"
              min-width="100"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.reportCount || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              min-width="100"
              :show-overflow-tooltip="true"
              prop="caseCount"
              label="用户案例数"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.caseCount || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              min-width="100"
              :show-overflow-tooltip="true"
              prop="serverCount"
              label="服务人数"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.serverCount || 0 }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column
              min-width="100"
              :show-overflow-tooltip="true"
              prop="aveReply"
              label="响应时间"
            >
              <template slot-scope="scope">
                <span
                  :class="[
                    scope.row.aveReply && scope.row.aveReply >= 1800
                      ? 'danger'
                      : 'success',
                  ]"
                  >{{ getReplyTime(scope.row.aveReply) }}</span
                >
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              min-width="140"
              :show-overflow-tooltip="true"
              prop="createTime"
              label="投诉数"
            >
            </el-table-column> -->
            <el-table-column fixed="right" label="操作" width="140">
              <template slot-scope="scope">
                <div class="operation-button">
                  <el-button
                    type="text"
                    @click="handlePerformanceDetail(scope.row)"
                    >绩效详情</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pager" v-if="list.length > 0">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.currentPage"
            :page-sizes="page.pageSizes"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.sums"
            background
          ></el-pagination>
        </div>
      </div>
    </div>
    <TipsDialog :visible.sync="showTipsVisible"></TipsDialog>
  </div>
</template>

<script>
import Axios from "axios";
import { apiJava } from "@/api/root";
import { downLoadFile } from "@/utils/downLoadFile";
import {
  getFirstDay,
  getLastDay,
  getLastMonthFirstDay,
  getLastMonthLastDay,
} from "@/utils/getNDate.js";
import page from "@/mixin/page";
import {
  consultantPerformanceList,
  getOrgTreeOld,
  scoreDetail,
} from "@/api/index";
export default {
  components: {
    TipsDialog: () => import("./components/TipsDialog"),
  },
  mixins: [page],
  data() {
    return {
      tableHeight: "auto",
      loading: false,
      exportLoading: false,
      scoreLoading: false,
      showTipsVisible: false,
      list: [],
      form: {
        consultantName: "",
        monthRange: [],
        deptIds: "",
        selectDate: "",
      },
      consultantTypeOptions: [
        { label: "全部", value: 1 },
        { label: "内部顾问", value: 2 },
        { label: "外部顾问", value: 3 },
      ],
      taskStatusOptions: [
        { label: "全部", value: 3 },
        { label: "进行中", value: 0 },
        { label: "未开始", value: 1 },
        { label: "已完成", value: 2 },
      ],
      currentScoreList: [
        { label: "用户评价总平均分", value: "" },
        { label: "服务态度平均分", value: "" },
        { label: "服务质量平均分", value: "" },
        { label: "服务效率平均分", value: "" },
      ],
      depTree: [],
      selectedRow: {},
      scoreMap: {},
    };
  },
  computed: {
    pickerOptions() {
      return {
        disabledDate(time) {
          const date1 = new Date("2024-01-01");
          const date2 = new Date(
            new Date().getFullYear() +
              "-" +
              ("0" + (new Date().getMonth() + 1)).substr(-2) +
              "-" +
              ("0" + new Date().getDate()).substr(-2)
          );
          const diff = date2 - date1 + 60 * 60 * 24 * 1000;
          return (
            time.getTime() < Date.now() - diff || Date.now() < time.getTime()
          );
        },
      };
    },
  },
  async created() {
    window.addEventListener("resize", this.getHeight);
    this.getOrgTreeOld();
    this.getDefaultDay();
  },
  mounted() {
    this.getHeight();
  },
  destroyed() {
    window.removeEventListener("resize", this.getHeight);
  },
  methods: {
    handleShowPopover() {
      this.showTipsVisible = true;
    },
    getReplyTime(val) {
      if (val == 0 || val == null) {
        return "0秒";
      } else {
        let hour = parseInt(val / 3600);
        let min = parseInt((val % 3600) / 60);
        let sec = parseInt(val % 60);
        return hour > 0
          ? `${hour}小时${min}分${sec}秒`
          : min > 0
          ? `${min}分${sec}秒`
          : `${sec}秒`;
      }
    },
    handleGetScore(row) {
      if (this.scoreMap[row.consultantId]) {
        this.currentScoreList = this.scoreMap[row.consultantId];
        return;
      }
      this.scoreLoading = true;
      let params = {
        consultantId: row.consultantId,
      };
      const year = this.form.monthRange[1].slice(0, 4);
      const month = this.form.monthRange[1].slice(5, 7);
      const lastDay = this.getLastDay(year, month);
      // params.startTime = this.form.monthRange[0] + " 00:00:00";
      params.startTime = this.form.selectDate[0] + " 00:00:00";

      // params.endTime =
      //   this.form.monthRange[1].slice(0, 7) + "-" + lastDay + " 23:59:59";
      params.endTime = this.form.selectDate[1] + " 23:59:59";
      scoreDetail(params)
        .then((res) => {
          if (res.code == 200) {
            let temp = [
              {
                label: "用户评价总平均分",
                value: row.userRate || "-",
              },
              {
                label: "服务态度平均分",
                value: res.data?.qualityScore || "-",
              },
              {
                label: "服务质量平均分",
                value: res.data?.qualityScore || "-",
              },
              {
                label: "服务效率平均分",
                value: res.data?.efficiencyScore || "-",
              },
            ];
            this.scoreMap[row.consultantId] = temp;
            this.currentScoreList = temp;
          } else {
            this.scoreLoading = false;
            this.$message.error(res.status_desc);
          }
        })
        .finally(() => {
          this.scoreLoading = false;
        });
    },
    getLastDay(year, month) {
      const date = new Date(year, month, 0);
      return date.getDate();
    },
    getDefaultDay() {
      const date = new Date();
      const today = date.getDate();
      // 过了5号就默认当月，否则默认上个月
      if (today > 5) {
        const firstDay = getFirstDay();
        const lastDay = getLastDay();
        this.$set(this.form.monthRange, 0, firstDay);
        this.$set(this.form.monthRange, 1, lastDay);
      } else {
        const firstDay = getLastMonthFirstDay();
        const lastDay = getLastMonthLastDay();
        this.$set(this.form.monthRange, 0, firstDay);
        this.$set(this.form.monthRange, 1, lastDay);
      }
      this.form.selectDate = this.form.monthRange;
      this.getData();
    },
    getData() {
      this.loading = true;
      let params = {
        deptIds:
          Array.isArray(this.form.deptIds) && this.form.deptIds.length
            ? this.form.deptIds[this.form.deptIds.length - 1]
            : "",
        consultantName: this.form.consultantName,
        pageNo: this.page.currentPage,
        pageSize: this.page.pageSize,
      };
      const year = this.form.monthRange[1].slice(0, 4);
      const month = this.form.monthRange[1].slice(5, 7);
      const lastDay = this.getLastDay(year, month);
      params.startTime = this.form.selectDate[0] + " 00:00:00";
      params.endTime = this.form.selectDate[1] + " 23:59:59";
      consultantPerformanceList(params)
        .then((res) => {
          if (res.code == 200) {
            this.list = res.data;
            this.page.sums = +res.pageparam.sums;
          } else {
            this.loading = false;
            this.$message.error(res.status_desc);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async getOrgTreeOld() {
      const params = {};
      const res = await getOrgTreeOld(params);
      if (res.code === "200") {
        this.depTree = res.data;
      }
    },
    getHeight() {
      this.tableHeight =
        window.innerHeight - this.$refs.searchBar.offsetHeight - 220;
    },
    handlePerformanceDetail(row) {
      let consultantInfo = row;
      consultantInfo.monthRange = this.form.selectDate;
      sessionStorage.setItem("consultantInfo", JSON.stringify(row));
      const url = this.$router.resolve({
        path: "/performance/performanceDetail",
      }).href;

      // 打开新的浏览器标签页
      const newTab = window.open(url, "_blank");
      // 检查是否成功打开新窗口，因为有些浏览器可能会阻止弹窗
      if (!newTab) {
        alert("未能成功打开新标签页，请允许浏览器弹出窗口");
      }
      // this.$router.push({
      //   path: "/performance/performanceDetail",
      // });
    },
    exportAll() {
      this.exportLoading = true;
      let params = {
        consultantName: this.form.consultantName,
        deptIds:
          Array.isArray(this.form.deptIds) && this.form.deptIds.length
            ? this.form.deptIds[this.form.deptIds.length - 1]
            : "",
      };
      const year = this.form.monthRange[1].slice(0, 4);
      const month = this.form.monthRange[1].slice(5, 7);
      const lastDay = this.getLastDay(year, month);
      params.startTime = this.form.selectDate[0] + " 00:00:00";

      params.endTime = this.form.selectDate[1] + " 23:59:59";
      Axios({
        method: "post",
        url: apiJava + "/api-career/performance/month/list/export",
        data: params,
        responseType: "arraybuffer",
        headers: {},
        timeout: "60000",
      })
        .then((res) => {
          downLoadFile(res, "顾问绩效数据.xlsx");
        })
        .catch(() => {
          this.$message.error("导出失败");
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
    async handleSearch() {
      console.log("form.selectDate", this.form.selectDate);
      this.$set(this.page, "currentPage", 1);
      this.getData();
    },
    handleReset() {
      this.form.consultantName = "";
      this.form.deptIds = [];
      this.handleSearch();
    },
  },
};
</script>

<style>
.el-popover.el-popper.el-popover-self {
  min-width: 20px !important;
}
</style>

<style lang="scss" scoped>
.report-list {
  background: url("../../../assets/images/bigBg.png") no-repeat;
  background-position: center;
  background-size: 100% 100%;
  .bread {
    margin: 24px 24px 16px 24px;
    ::v-deep .content-wrapper .content .el-breadcrumb {
      padding: 0;
      background-color: transparent;
    }
    ::v-deep .el-breadcrumb__separator {
      color: #000;
    }
    ::v-deep .el-breadcrumb__inner {
      color: #8892a6;
    }
    ::v-deep .el-breadcrumb__item:last-of-type .el-breadcrumb__inner {
      color: #222;
    }
  }
  .rl-content {
    margin: 0px 12px 0 12px;
    .search-box {
      padding: 22px 24px 0 22px;
      border-bottom: 1px solid #e8e8e8;
    }
    .table-wrap {
      box-shadow: 0 0 0 0;
      padding: 20px 24px;
      overflow: hidden;
      .operate-bar {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        .tips {
          font-size: 14px;
          color: $primary_color;
          margin-left: 24px;
        }
        /deep/ .el-button--small.is-round {
          font-size: 14px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          color: #555555;
        }
      }
      .operation-button {
        /deep/ .el-button--text {
          font-weight: 400;
        }
      }
      .my-header {
        cursor: pointer;
      }
    }
    .pointer {
      cursor: pointer;
    }
    .danger {
      color: #f56c6c;
    }
    .success {
      color: #67c23a;
    }
  }
}

.list-box {
  .item {
    display: flex;
    justify-content: space-between;
    color: #999;
    padding: 3px 0;
    &:first-child {
      font-weight: 600;
      color: #000;
    }
    .name {
      margin-right: 38px;
    }
  }
}

/deep/ .el-col-12 {
  width: 25%;
}

/deep/ .el-range-editor--small .el-range-separator {
  line-height: 24px;
  font-size: 13px;
  width: 25px;
}
/deep/ .header_name_style {
  font-size: 14px;
  font-family: PingFang-SC, PingFang-SC;
  font-weight: bold;
  color: #6c7481;
}
</style>
